package com.zky.service.impl;

import com.zky.entity.User;
import com.zky.mapper.UserMapper;
import com.zky.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    @Override
    public void register(User user) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 如果用户名是 admin1，设置为管理员角色
        if ("admin1".equals(user.getUsername())) {
            user.setRole("admin");
        } else {
            user.setRole("user");
        }
        
        userMapper.insert(user);
    }

    @Override
    public User login(String username, String password) {
        // 查找用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 清除密码后返回
        user.setPassword(null);
        return user;
    }
} 